/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bionic.ce.connections;

import com.bionic.ce.manager.Config;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.*;

/**
 *
 * @author Artem
 */
public class ConnectionPool {
    
    private static int count=0;
    private static final int MAXCOUNT=20;
    private static List<Connection> connectionPool = new ArrayList(MAXCOUNT);
    

    public synchronized Connection getConnection() throws SQLException, ClassNotFoundException {
        Connection con = null;
        
            if ((connectionPool.isEmpty())&(count<=MAXCOUNT)) {
                try {
                Class.forName(Config.getInstance().getProperty(Config.MYSQLDRIVER));
                try {
                    con = DriverManager.getConnection(Config.getInstance().getProperty(Config.MYSQLURL));
                    count++;
                } catch (SQLException e) {
                    String MYSQLURL=Config.getInstance().getProperty(Config.MYSQLURL);
                    throw new SQLException("Connection problems during attempt to connect to "+MYSQLURL,e);
                }
        } catch (ClassNotFoundException e) {
            throw new ClassNotFoundException("The MySQL JDBC driver was not found",e);
        }
            } else {
                con = connectionPool.get(0);
                connectionPool.remove(0);
            }

        return con;
    }
    
    public synchronized void free(Connection con) {
        connectionPool.add(con);
    }
    
}
